// models\index.js
var request = require('request');
const axios = require('axios');
var token = "ef58fd9d9b3d0016cc88a671b8c6c389a7c8b9c6"; // 使用你的Access Token

async function findUserByOpenid(openid) {
  return new Promise((resolve, reject) => {
    var opt = {
      uri: 'https://cloud.minapp.com/oserve/v2.4/table/users/record/',  // 对应表 ID
      method: 'GET',
      headers: {
        Authorization: `Bearer ${token}`,
      },
      qs: {
        where: JSON.stringify({ "openid": openid }),  // 查找匹配 openid 的记录
        limit: 1    // 只需要一条匹配记录
      }
    }

    request(opt, function(err, res, body) {
      if (err) {
        console.error("检索用户信息失败", err);
        reject(err);
      } else {
        const data = JSON.parse(body);
        if (data.objects && data.objects.length > 0) {
          resolve(data.objects[0]);  // 返回匹配的第一条记录
        } else {
          resolve(null);  // 没有匹配的记录
        }
      }
    });
  });
}

async function addUser(openid, session_key, nickname, avatarUrl) {
  const existingUser = await findUserByOpenid(openid);
  if (existingUser) {
    console.log("用户已存在于知晓云", existingUser);
    const url = `https://cloud.minapp.com/oserve/v2.4/table/users/record/${existingUser.id}/`;
    const headers = {
      Authorization: `Bearer ${token}`,
      "Content-Type": "application/json"
    };

    const lastTokenUpdateTime = Math.floor(Date.now() / 1000);

    const data = {
      session_key: session_key,
      nickname: nickname,
      avatarUrl: avatarUrl,
      lastTokenUpdate: lastTokenUpdateTime,
    };

    try {
      const response = await axios.put(url, data, { headers });
      console.log("用户信息已更新到知晓云", response.data);
      return response.data;
    } catch (error) {
      console.error("更新用户信息至知晓云失败", error);
      throw error;
    }
  } else {
    const url = "https://cloud.minapp.com/oserve/v2.4/table/users/record/";
    const headers = {
      Authorization: `Bearer ${token}`,
      "Content-Type": "application/json"
    };

    const lastTokenUpdateTime = Math.floor(Date.now() / 1000);

    const data = {
      openid: openid,
      session_key: session_key,
      nickname: nickname,
      avatarUrl: avatarUrl,
      lastTokenUpdate: lastTokenUpdateTime,
    };

    try {
      const response = await axios.post(url, data, { headers });
      console.log("用户信息已保存到知晓云", response.data);
      return response.data;
    } catch (error) {
      console.error("保存用户信息至知晓云失败", error);
      throw error;
    }
  }
}

module.exports = {
  addUser,
  findUserByOpenid
};
